package week_4.practice;

import week_1.practice.LinearNode;

/**
 * LinkedOrderedList represents a singly linked implementation of an
 * ordered list.
 *
 * @author Lewis and Chase
 * @version 4.0
 */
public class LinkedOrderedList<T> extends LinkedList<T>
        implements OrderedListADT<T>
{
    /**
     * Creates an empty list.
     */
    public LinkedOrderedList()
    {
        super();
    }

    /**
     * Adds the specified element to this list at the location determined by
     * the element's natural ordering. Throws a NonComparableElementException
     * if the element is not comparable.
     *
     * @param element the element to be added to this list
     * @throws NonComparableElementException if the element is not comparable
     */
    @Override
    public void add(T element)
    {
        if (!(element instanceof Comparable)) {
            throw new NonComparableElementException("LinkedList");
        }
        Comparable<T> comparableElement = (Comparable<T>) element;
        LinearNode node = new LinearNode(comparableElement);
        LinearNode temp = head;
        for (int i = 0; i < count-1; i++)
        {
            temp = temp.getNext();
        }

        if (size() == 0)
        {
            head = node;//链表为空直接插入
            count++;
            return;
        }
        else if (comparableElement.compareTo(head.getElement()) < 0)
        {//插入在链表头部
            node.setNext(head);
            head = node;
            count++;
            return;
        }
        else if (comparableElement.compareTo((T) temp.getElement()) > 0)
        {//插入在链表尾部
            temp.setNext(node);
            count++;
        }
        else
            {//插入在链表中间
            LinearNode current = head;
            LinearNode currentnode = current.getNext();
            for (int i = 0; i < count - 1; i++) {
                if (comparableElement.compareTo((T) currentnode.getElement()) < 0) {
                    current.setNext(node);
                    node.setNext(currentnode);
                    count++;
                    return;
                }
                current = currentnode;
                currentnode = currentnode.getNext();
            }
        }
    }
}
